package com.junchenrobot.mes.dao;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.junchenrobot.mes.domain.AgvWork;
import com.junchenrobot.mes.mapper.AgvWorkMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Agv作业Dao
 *
 * @author SeaWave
 */
@Component
public class AgvWorkDao {

    private final AgvWorkMapper agvWorkMapper;

    @Autowired
    public AgvWorkDao(AgvWorkMapper agvWorkMapper) {
        this.agvWorkMapper = agvWorkMapper;
    }

    /**
     * 批量查询AGV作业
     *
     * @return {@link List}<{@link AgvWork}>
     */
    public List<AgvWork> listAgvWork() {
        return new LambdaQueryChainWrapper<>(agvWorkMapper).eq(AgvWork::getStatus, 1)
                .orderByAsc(AgvWork::getTime)
                .list();
    }


    /**
     * 替换AGV作业状态
     * 将一种状态更新为另一种状态
     *
     * @param status      AGV作业状态
     * @param otherStatus AGV作业其他状态
     * @return int
     */
    public int replaceAgvStatus(Integer status, Integer otherStatus) {
        UpdateWrapper<AgvWork> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status", status).eq("status", otherStatus);
        return agvWorkMapper.update(null, updateWrapper);
    }

    /**
     * 获得自主移动小车工作
     *
     * @return {@link AgvWork}
     */
    public AgvWork getAgvWork(Integer line, Integer spinning) {
        return new LambdaQueryChainWrapper<>(agvWorkMapper).eq(AgvWork::getLine, line)
                                                           .eq(AgvWork::getSpinNo, spinning)
                                                           .one();
    }


    /**
     * 获取最新的任务作业
     *
     * @return {@link AgvWork}
     */
    public AgvWork getAgvWork(Long agvWorkId) {
        return agvWorkMapper.selectById(agvWorkId);
    }

    /**
     * 更新工作状态
     *
     * @param status 状态
     * @param id     任务id
     * @return boolean
     */
    public boolean updateWorkStatus(Long id, Integer status) {
        LambdaUpdateWrapper<AgvWork> wrapper = new LambdaUpdateWrapper<AgvWork>().set(AgvWork::getStatus, status)
                                                                                 .eq(AgvWork::getId, id);
        return agvWorkMapper.update(null, wrapper) > 0;
    }


}
